#include <REGX52.H>
#include "DS18B20.h"
#include "LCD1602.h"
#include "Delay.h"
#include "AT24C02.h"
#include "Key.h"
#include "Timer0.h"

float t, tShow;
char tLow, tHigh;
unsigned char keyNum;

void main()
{
    DS18B20_convert_t();  // 上电先转换一次温度，防止第一次读数据错误
    Delay(1000);  // 等待转换完成
    tHigh = AT24C02_readbyte(0);
    tLow = AT24C02_readbyte(1);
    if (tHigh > 125 || tLow < -55 || tHigh <= tLow)
    {
        tHigh = 20;
        tLow = 15;
    }
    LCD_Init();
    LCD_ShowString(1, 1, "T:");
    LCD_ShowString(2, 1, "TH:");
    LCD_ShowString(2, 9, "TL:");
    LCD_ShowSignedNum(2, 4, tHigh, 3);
    LCD_ShowSignedNum(2, 12, tLow, 3);
    Timer0_Init();
	while (1)
	{
        keyNum = Key();
        // 温度读取及显示
		DS18B20_convert_t();
        t = DS18B20_read_t();
        if (t < 0)
        {
            LCD_ShowChar(1, 3, '-');
            tShow = -t;
        }
        else
        {
            LCD_ShowChar(1, 3, '+');
            tShow = t;
        }
        LCD_ShowNum(1, 4, tShow, 3);
        LCD_ShowChar(1, 7, '.');
        LCD_ShowNum(1, 8, (unsigned long)(tShow * 100) % 100, 2);
        
        // 阈值判断及显示
        if (keyNum)
        {
            if (keyNum == 1)
            {
                tHigh++;
                if (tHigh > 125)
                {
                    tHigh = 125;
                }
            }
            if (keyNum == 2)
            {
                tHigh--;
                if (tHigh <= tLow)
                {
                    tHigh++;
                }
            }
            if (keyNum == 3)
            {
                tLow++;
                if (tLow >= tHigh)
                {
                    tLow--;
                }
            }
            if (keyNum == 4)
            {
                tLow--;
                if (tLow < -55)
                {
                    tLow = -55;
                }
            }
        }
        LCD_ShowSignedNum(2, 4, tHigh, 3);
        LCD_ShowSignedNum(2, 12, tLow, 3);
        AT24C02_writebyte(0, tHigh);
        Delay(5);
        AT24C02_writebyte(1, tLow);
        Delay(5);
        if (t > tHigh)
        {
            LCD_ShowString(1, 13, "OV:H");
        }
        else if (t < tLow)
        {
            LCD_ShowString(1, 13, "OV:L");
        }
        else
        {
            LCD_ShowString(1, 13, "    ");
        }
	}
}

void Timer0_Rountine(void) interrupt 1
{
    static unsigned int t0_count;
    TL0 = 0x18;		//设置定时初始值
    TH0 = 0xFC;		//设置定时初始值
    t0_count++;
    if (t0_count >= 20)
    {
        t0_count = 0;
        Key_loop();  // 每20ms调用一次按键驱动函数
    }
}